<?php

namespace App\Repositories;

use Exception;
use Illuminate\Support\Facades\Storage;

class UploadRepository
{
    public function uploadFile($request, \Closure $closure = null)
    {
        // 文件对象
        $fileObj = $request->file('file');

        if (is_callable($closure)) {
            list($fileName, $filePath) = $closure($fileObj);
        } else {
            $fileName = $fileObj->hashName();
            $filePath = "public/import/" . date("Ymd", time());
        }

        if (!Storage::putFileAs($filePath, $fileObj, $fileName)) {
            throw new Exception("上传失败");
        }

        // 完整路径
        $fullPath = storage_path() . '/app/' . $filePath . '/' . $fileName;

        // 安全性校验
        checkFileHex($fullPath);

        return $fullPath;
    }
}
